<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        
        .header {
            height: 150px;
            background-color: royalblue;
        }
        
        .banner {
            height: 250px;
            background-color: salmon;
        }
        
        .main {
            height: 1000px;
            background-color: sienna;
        }
        
        .slider-bar {
            position: absolute;
            width: 45px;
            height: 130px;
            background-color: skyblue;
            top: 200px;
            left: 50%;
            margin-left: 600px;
        }
        
        .slider-bar .goBack {
            display: none;
            height: 50px;
            border: 1px solid gray;
        }
        
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
    <script>
        // 1.获取元素
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        var bannerTop = banner.offsetTop;
        console.log(bannerTop); //banner距离顶部的距离
        // 当侧边栏固定定位之后应该变化的数值
        console.log(sliderbar.offsetTop); // 侧边目录距离顶部的距离
        var sliderTop = sliderbar.offsetTop - bannerTop; // 固定定位后的位置
        console.log(sliderTop);
        // 获取main主体元素
        var main = document.querySelector('.main');
        var goBack = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        // 2.页面滚动事件
        document.addEventListener('scroll', function() {
            //console.log(window.pageYOffset); //页面被卷去的头部
            //当我们页面被卷去的头部大于等于了*** 此时侧边栏就要改为固定定位
            if (window.pageYOffset >= bannerTop) {
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderTop + 'px'; //30px
            } else {
                sliderbar.style.position = 'absolute'
                sliderbar.style.top = '200px';
            }
            // 4.当页面滚动到main盒子就显示goBack模块
            if (window.pageYOffset >= mainTop) {
                goBack.style.display = 'block';
            } else {
                goBack.style.display = 'none';
            }
        })
    </script>
</body>

</html>